<template>
  <div class="container">
    <div>
      <van-nav-bar
        title="信息发布"
        left-text="返回"
        @click-left="onClickLeft"
        left-arrow
      />
    </div>

    <div>
      <van-cell  title="请选择发布类型" required title-class="titleclass"   v-model="fblxname" center is-link @click="showFblx" />
      <van-cell  title="请选择所属大类" required title-class="titleclass"   v-model="spdlname" center is-link @click="showSpdl" />

      <div style="padding-top: 10px;width: 98%;">
         <textarea rows="10"  class="textarea" placeholder="请输入发布内容" v-model="content">
         </textarea>
      </div>
      <div style="padding-top: 10px;padding-left: 13px;color: #B2B2B2;font-size: 18px;">图片上传</div>
      <div style="padding-left: 10px;padding-top: 10px;">
        <div class="box" v-for="item in images " >
          <img :src="item" width="80" height="80" alt="" />
          <div class="clear">
            <img src="../images/del.png" width="20" height="20" @click="delImgs({item})"/>
          </div>
        </div>
        <div class="box" >
          <img src="../images/add.png" width="60" height="60" alt="" @click="selectTp"/>
          <input type="file" accept="image/*" hidden id="uploadfileid" @change="fileSelected"  capture='camera' />
       </div>
      </div>

      <van-field
        label=""
        required
        left-icon="contact"
        placeholder="请输入您的姓名"
        v-model="fbrname"
      />
      <van-field
        clearable
        label=""
        required
        left-icon="phone-o"
        v-model="fbrdh"
        placeholder="请输入您的手机号"
      />

      <div style="padding-left: 20px;padding-right: 20px;padding-top:10px;padding-bottom: 30px;">
        <van-button type="primary" @click="dofabu" size="large" color="#FF6900" round>立即发布</van-button>
      </div>

    </div>

    <van-action-sheet v-model="show" :actions="actions" @select="onSelectfblx" />
    <van-action-sheet v-model="showspdl" :actions="platformProductCategory" @select="onSelectSpdl" />

  </div>
</template>

<script>
import { queryPlatformProductCategory, saveShareInfo, uploadShareImg } from '../../api/api'
import { Dialog, Toast } from 'vant'
import weui from 'weui.js'
import 'weui'

export default {
  name: 'Search',
  data() {
    return {
      actions: [{ name: '找产品', id: '1' }, { name: '招代理商', id: '2' }],
      fblxname: '请选择发布类型',
      gxlx: '',
      platformProductCategory: [],
      showfblx: false,
      placeholder: '请输入要发布的内容',
      content: '',
      fileList: [],
      images: [],
      categoryId: '',
      show: false,
      phone: '',
      sjherrormsg: '',
      mzsmflag: '',
      qybtnflag: true,
      checked: false,
      xcxopenid: '',
      loading: true,
      showspdl: false,
      spdlname: '请选择所属商品大类',
      spdldata: [],
      fbrname: '',
      fbrdh: ''
    }
  },
  created() {
    const agencyId = this.$store.getters.agencyId
    if (agencyId && typeof agencyId !== 'undefined') {
      this.$store.dispatch('setAgencyId', agencyId)
    }
    this.queryPlatformProductCategory()
    const xtname = this.viewczxt()
    const that = this
    if (xtname == 'Android') {
      document.addEventListener('message', function(msg) {
        console.log(msg)
        that.images.push(msg.data + '')
        // 如果需要获取msg里面的值。需要msg.data。
        // 当时这个坑卡了好久，因为不方便查看msg里面的东西，直接用msg.是获取不到东西的。
        // 还有，记住使用  JSON.parse(msg.data)  才能获取到你的东西!!!
      })
    } else {
      window.onload = function() {
        window.addEventListener('message', function(event) {
          console.log('app发送信息：')
          console.log(event.data)
          that.images.push(msg.data + '')
        })
      }
    }
  },
  methods: {

    // 识别操作系统
    viewczxt() {
      var u = navigator.userAgent; var app = navigator.appVersion
      var isXiaomi = u.indexOf('XiaoMi') > -1 // 小米手机
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1 // 其它安卓
      var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios
      if (isAndroid) {
        return 'Android'
      } else if (isIOS) {
        if (isXiaomi) {
          return 'Android'
        } else {
          return 'Ios'
        }
      }
    },

    toFabu() {
      this.$router.push({ path: '/fabu', query: {}})
    },

    showFblx() {
      this.show = true
    },

    showSpdl() {
      this.showspdl = true
    },

    onClosefblx() {
      this.show = false
    },

    onSelectfblx(item) {
      console.log(item)
      this.fblxname = item.name
      this.gxlx = item.id
      this.show = false
    },

    onSelectSpdl(item) {
      console.log(item)
      this.spdlname = item.name
      this.categoryId = item.categoryId
      this.showspdl = false
    },

    onClickLeft() {
      this.$router.go(-1) // 返回上一层
    },

    dofabu() {
      const agencyId = this.$store.getters.agencyId
      if (!this.gxlx) {
        Toast.fail('请选择供需类型')
        return
      }
      if (!this.categoryId) {
        Toast.fail('请选择所属大类')
        return
      }
      if (!this.content) {
        Toast.fail('请填写发布内容')
        return
      }
      if (!this.fbrname) {
        Toast.fail('请填写您的姓名')
        return
      }
      if (!this.fbrdh) {
        Toast.fail('请填写您的电话')
        return
      }
      const param = { agencyid: agencyId, gxlx: this.gxlx, spdl: this.categoryId, content: this.content, images: this.images.toString(), fbrname: this.fbrname, fbrdh: this.fbrdh }
      saveShareInfo(param).then(response => {
        if (response.code === 200) {
          Dialog.alert({
            title: '',
            message: '提交成功'
          }).then(() => {
            // on close
            this.$router.go(-1) // 返回上一层
          })
        } else {
          Toast.fail(response.msg)
        }
      })
    },

    queryPlatformProductCategory() {
      const param = {}
      queryPlatformProductCategory(param).then(response => {
        console.log(response.data)
        this.platformProductCategory = response.data
      })
    },

    /**
       * 上传附件
       * @param {*} event
       */
    uploadImgs(file, name) {
      const formData = new FormData()
      formData.append('file', file.file)
      formData.append('type', 'quanzi')
      const fileList = []
      uploadShareImg(formData).then(response => {
        console.log(response)
        if (response.code == 200) {
          fileList.push(response.url)
          this.images.push(response.url + '')
          this.fileList.concat(fileList)
        }
      })
    },

    /**
       * 删除附件
       * @param {*} e
       */
    delImgs: function(item) {
      console.log(item)
      console.log(this.images)
      const that = this
      const images = that.images
      const length = images.length
      for (var i = 0; i < length; i++) {
        if (images[i] == item.item) {
          that.images.splice(i, 1)
        }
      }
    },

    selectTp() {
      window.postMessage('camera')
      document.getElementById('uploadfileid').click()
    },

    fileSelected() {
      var file = document.getElementById('uploadfileid').files[0]
      if (file) {
        var fileSize = 0
        if (file.size > 1024 * 1024) { fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB' } else { fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB' }

        console.log(file.name)
        console.log(fileSize)
        console.log(file.type)

        const formData = new FormData()
        formData.append('file', file)
        formData.append('type', 'quanzi')
        const fileList = []
        uploadShareImg(formData).then(response => {
          console.log(response)
          if (response.code == 200) {
            fileList.push(response.url)
            this.images.push(response.url + '')
            this.fileList.concat(fileList)
            console.log(this.fileList)
            console.log(this.images)
          }
        })
      }
    }

  }
}
</script>

<style scoped>
  .container{
    width: 100%;
    background-color: white;
  }

  .container::-webkit-scrollbar {
    display: none; /* Chrome Safari */
  }

  .textarea {
    font-size: 16px;
    margin: 5%;
    background-color: #ffffff;
    width: 90%;
    height: 150px;
    border-radius: 5px;
    border: 1px solid #B2B2B2;
  }

  .rownr{
    display: flex;
    flex-direction: row;
  }
  .box {
    position: relative;
    display: inline-block;
    padding-left: 12px;
  }
  .box .clear {
    position: absolute;
    top: 0;
    right: 0;
  }

</style>
